#!/usr/bin/env python
# coding: utf-8

from wcferry import Wcf
import time
from threading import Thread

wcf = Wcf()

msg_types = wcf.get_msg_types()

contacts = wcf.get_contacts()

def handle_message():
        try:
            msg = wcf.get_msg(block=False)
        except:
            return
        # if msg.sender != wx_id:
        #     continue

        if msg.type not in {1, 3, 34, 47, 66, 9999, 10000, 10002, 822083633, 922746929}:
            return

        if msg.from_group():
            # 群消息
            groupname = wcf.get_info_by_wxid(msg.roomid)['name']
            sender_name = wcf.get_alias_in_chatroom(msg.sender, msg.roomid)
            possible_friend = wcf.get_info_by_wxid(msg.sender)
            sender = groupname + '->' + sender_name
        elif msg.from_self():
            sender = '自己'
        else:
            sender = wcf.get_info_by_wxid(msg.sender)['name']

        # 自定义筛选
        #if not msg.from_group():
        #    continue
        #if msg.roomid != wx_id:
        #    continue

        if msg.type == 3:
            content = wcf.get_ocr_result(msg.extra)
        else:
            content = msg.content

        print('[' + sender, ']:' + content)


if __name__ == '__main__':
    name = input("监听的聊天:")
    if not name:
        name = '靠力气赚钱心里才踏实'
    for contact in contacts:
        if contact['name'] == name:
            wx_id = contact['wxid']
    
    print('开始监听' + wx_id)
    print(wcf.get_msg_types())
    if not wx_id:
        print('没有这个聊天')
        exit(-1)
    
    if not wcf.is_login():
        print('wechat is not running.')
        exit(-1)
    if not wcf.is_receiving_msg():
        wcf.enable_receiving_msg()
    
    t = Thread(target=message_handler)
    t.start()

    while True:
        msg = input()
        if 'q' == msg:
            #wcf.disable_recv_msg()
            wcf.cleanup()
            t._stop()
            exit(0)
        else:
            wcf.send_text(msg, wx_id)

